﻿using Sidvall.IdentityManager.UI.Entities;
using System.Linq;
using System.Threading.Tasks;

namespace Sidvall.IdentityManager.UI.ViewModels
{
	public class UserProfileViewModel : AspNetUsersViewModel
	{
		#region Public Members

		#region NameClaim

		public AspNetUserClaims NameClaim
		{
			get
			{
				if (this.ActiveEntity == null)
					return null;
				if (this.ActiveEntity.AspNetUserClaims == null)
					return null;
				return (from o in this.ActiveEntity.AspNetUserClaims
						where o.ClaimType.Equals(Sidvall.Security.ClaimTypes.Name, System.StringComparison.OrdinalIgnoreCase)
						select o).FirstOrDefault();
			}
		}

		#endregion
		#region UserName

		public string UserName
		{
			get
			{
				if (this.NameClaim == null)
					return null;
				return this.NameClaim.ClaimValue;
			}
			set
			{
				AspNetUserClaims item;

				if (this.ActiveEntity == null)
					return;
				item = this.NameClaim;
				if (!string.IsNullOrWhiteSpace(value))
				{
					if (this.ActiveEntity.AspNetUserClaims == null)
						this.ActiveEntity.AspNetUserClaims = new AspNetUserClaimsCollection();
					if (item == null)
					{
						item = new AspNetUserClaims()
						{
							UserId = this.ActiveEntity.Id,
							ClaimType = Sidvall.Security.ClaimTypes.Name,
						};
						this.ActiveEntity.AspNetUserClaims.Add(item);
					}
					item.ClaimValue = value;
				}
				else
				{
					if (item == null)
						return;
					this.ActiveEntity.AspNetUserClaims.Remove(item);
				}
			}
		}

		#endregion

		#region LoadItemAsync

		protected override async Task<AspNetUsers> LoadItemAsync()
		{
			AspNetUsers item;
			string name;

			name = Sidvall.SystemContext.Current.PrincipalManager.CurrentIdentityName;
			item = await SystemContext.Current.DataPortal.AspNetUsersManager.GetItemByUserNameAsync(name);
			if (item != null)
			{
				await item.LoadAspNetUserClaimsAsync();
				await item.LoadAspNetUserLoginsAsync();
			}
			return item;
		}

		#endregion
		#region StartAsync

		protected async override Task StartAsync()
		{
			await ViewModelManager.LoadCacheAsync(false, null, this.EntityCache);
			await DoLoadAsync();
		}

		#endregion

		#endregion
	}
}